package cn.yuyiling.jelly.sr.service.impl;

import cn.yuyiling.jelly.sr.api.LearningProgressService;
import cn.yuyiling.jelly.sr.mongodb.entity.UserLearningRecord;
import cn.yuyiling.jelly.sr.mongodb.repository.UserLearningRecordRepository;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

@DubboService
public class LearningProgressServiceImpl implements LearningProgressService {

    private static final Logger logger = LoggerFactory.getLogger(LearningProgressServiceImpl.class);

    @Autowired
    private UserLearningRecordRepository learningRecordRepository;

    /**
     * 记录知识点学习行为
     */
    @Override
    public String recordStudySession(String userId, String knowledgePointId) {
        UserLearningRecord record = new UserLearningRecord();
        record.setUserId(userId);
        record.setKnowledgePointId(knowledgePointId);
        record.setType(UserLearningRecord.RecordType.STUDY_KNOWLEDGE_POINT);
        record.setStartTime(new Date());
        record.setCreatedAt(new Date());
        return learningRecordRepository.save(record).getId();
    }

    /**
     * 结束知识点学习会话并记录时长
     */
    @Override
    public void endStudySession(String sessionId) {
        UserLearningRecord record = learningRecordRepository.findById(sessionId).orElse(null);
        if (record != null && record.getEndTime() == null) {
            record.setEndTime(new Date());
            learningRecordRepository.save(record);
        }
    }

    /**
     * 记录答题结果行为
     */
    @Override
    public String recordAnswerSession(String userId, String answerId) {
        UserLearningRecord record = new UserLearningRecord();
        record.setUserId(userId);
        record.setType(UserLearningRecord.RecordType.ANSWER);
        record.setStartTime(new Date());

        UserLearningRecord.QuizResult result = new UserLearningRecord.QuizResult();
        result.setAnswerId(answerId);
        record.setQuizResult(result);
        record.setCreatedAt(new Date());
        return learningRecordRepository.save(record).getId();
    }

    /**
     * 结束答题并记录时长
     */
    @Override
    public String recordAnswerResult(String sessionId, int score) {
        UserLearningRecord record = learningRecordRepository.findById(sessionId).orElse(null);
        if (record != null && record.getQuizResult() != null) {
            record.getQuizResult().setScore(score);
            record.setEndTime(new Date());
            return learningRecordRepository.save(record).getId();
        }
        return null;
    }

    @Override
    public Map<String, Integer> getDailyStudyDuration(String userId) {
        return aggregateByDay(userId);
    }

    @Override
    public Map<String, Integer> getWeeklyStudyDuration(String userId) {
        return aggregateByWeek(userId);
    }

    @Override
    public Map<String, Integer> getMonthlyStudyDuration(String userId) {
        return aggregateByMonth(userId);
    }

    private Map<String, Integer> aggregateByDay(String userId) {
        List<UserLearningRecord> records = learningRecordRepository.findByUserId(userId);
        Map<String, Integer> result = new HashMap<>();

        for (UserLearningRecord record : records) {
            if (record.getStartTime() != null && record.getEndTime() != null) {
                long duration = record.getEndTime().getTime() - record.getStartTime().getTime();
                String day = new SimpleDateFormat("yyyy-MM-dd").format(record.getStartTime());
                result.put(day, result.getOrDefault(day, 0) + (int)(duration / 60000)); // 分钟数
            }
        }
        return result;
    }

    private Map<String, Integer> aggregateByWeek(String userId) {
        List<UserLearningRecord> records = learningRecordRepository.findByUserId(userId);
        Map<String, Integer> result = new HashMap<>();

        for (UserLearningRecord record : records) {
            if (record.getStartTime() != null && record.getEndTime() != null) {
                long duration = record.getEndTime().getTime() - record.getStartTime().getTime();
                Calendar cal = Calendar.getInstance();
                cal.setTime(record.getStartTime());
                int week = cal.get(Calendar.WEEK_OF_YEAR);
                String key = String.format("%d-W%d", cal.get(Calendar.YEAR), week);
                result.put(key, result.getOrDefault(key, 0) + (int)(duration / 60000));
            }
        }
        return result;
    }

    private Map<String, Integer> aggregateByMonth(String userId) {
        List<UserLearningRecord> records = learningRecordRepository.findByUserId(userId);
        Map<String, Integer> result = new HashMap<>();

        for (UserLearningRecord record : records) {
            if (record.getStartTime() != null && record.getEndTime() != null) {
                long duration = record.getEndTime().getTime() - record.getStartTime().getTime();
                String month = new SimpleDateFormat("yyyy-MM").format(record.getStartTime());
                result.put(month, result.getOrDefault(month, 0) + (int)(duration / 60000));
            }
        }
        return result;
    }

    @Override
    public List<UserLearningRecord> findByUserId(String userId) {
        return learningRecordRepository.findByUserId(userId);
    }
}
